package com.congee02.autocrud.controller;

import com.congee02.autocrud.service.AbstractBaseCRUDService;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

public abstract class AbstractBaseCRUDController<T> {

    protected final AbstractBaseCRUDService<T> crudService;

    protected AbstractBaseCRUDController(AbstractBaseCRUDService<T> crudService) {
        this.crudService = crudService;
    }

    @PostMapping(CRUDEndPointPattern.INSERT)
    public T insert(@Valid T entity) {
        return crudService.insert(entity);
    }

    @PutMapping(CRUDEndPointPattern.UPDATE)
    public T update(@Valid T entity) {
        return crudService.update(entity);
    }

    @DeleteMapping(CRUDEndPointPattern.DELETE_BY_ID)
    public void deleteById(@Valid @NotNull Long id) {
        crudService.deleteById(id);
    }

    @GetMapping(CRUDEndPointPattern.FIND_BY_ID)
    public T findById(@Valid @NotNull Long id) {
        return crudService.findById(id);
    }

    @GetMapping(CRUDEndPointPattern.FIND_BY_PAGE)
    public Page<T> findByPage
            (@Valid @RequestParam(defaultValue = "0") @Min(value = 0) Integer pageIndex,
             @Valid @RequestParam(defaultValue = "20") @Min(value = 1) Integer pageSize) {
        return crudService.findByPage(pageIndex, pageSize);
    }

}
